﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CharitiesLib;
using System.IO;

namespace Charities.Forms
{
    public partial class PersonalForm : Form
    {
        int personId;
        Form fo=null;
        int userid;
        int worthyId;
        public bool is_loaded;
        MainWindow mainwindow;
        public delegate void UpdateFormHandler(object sender, UpdateFormEventArg e);
        public event UpdateFormHandler FormUpdated;
        public PersonalForm(int uid,int wpid,int pid, Form mdi,MainWindow main)
        {
            mainwindow = main;
            personId = pid;
            worthyId = wpid;
            fo = mdi;
            MdiParent = mdi;
            userid = uid;
            InitializeComponent();
        }
        ModelContainer ctx = new ModelContainer();
        Person p;
        private void PersonalForm_Load(object sender, EventArgs e)
        {
            if (personId > 0)
            {
                is_loaded = true;
                GetElementStates();
                p = ctx.People.Single(c => c.Id == personId);
                Person wp = ctx.People.Single(c => c.Id == p.Worthy.PersonId);
                txb_Amana.Text = p.Amana;
                if (p.DOB != null)
                    txb_BoxDOB.Text = p.DOB.Value.ToShortDateString();
                txb_BoxPoP.Text = p.POB;
                txb_FatherName.Text = p.FatherName;
                txb_FirstName.Text = p.FirstName;
                txb_LaNamest.Text = p.LastName;
                txb_MotherName.Text = p.MotherName;
                txb_NatNumber.Text = p.NationalNumber;
                txb_Qaid.Text = p.Qaid;
                txb_worthy_id.Text = p.WorthyId.ToString();
                txb_WorthyName.Text = wp.FirstName + " " + wp.FatherName + " " + wp.LastName;
                txb_job.Text = p.JobTitle;
                txb_healthStatus.Text = p.HealthStatus;
                if (p.PersonalPicture != null && p.PersonalPicture.Length > 5)
                    ReadtoPictureBox(p.PersonalPicture);

         
                cbo_Sex.Text = p.Sex;
            }
            else
            {
                txb_worthy_id.Text = worthyId.ToString();
                int wpi = ctx.Worthies.Where(w => w.Id == worthyId).FirstOrDefault().PersonId;

                Person wpe = ctx.People.Where(wp => wp.Id == wpi).FirstOrDefault();
                txb_WorthyName.Text = wpe.FirstName+" " +wpe.FatherName +" " + wpe.LastName;
                chk_Modefy.Checked = true;
                GetElementStates();
            }
        }
        private void GetElementStates()
        {
            txb_Amana.Enabled = chk_Modefy.Checked;
            txb_BoxDOB.Enabled = chk_Modefy.Checked;
            txb_BoxPoP.Enabled = chk_Modefy.Checked;
            txb_FatherName.Enabled = chk_Modefy.Checked;
            txb_FirstName.Enabled = chk_Modefy.Checked;
            txb_LaNamest.Enabled = chk_Modefy.Checked;
            txb_MotherName.Enabled = chk_Modefy.Checked;
            txb_NatNumber.Enabled = chk_Modefy.Checked;
            txb_healthStatus.Enabled = chk_Modefy.Checked;
            txb_job.Enabled = chk_Modefy.Checked;
            txb_Qaid.Enabled = chk_Modefy.Checked;
            cbo_Sex.Enabled = chk_Modefy.Checked;
            toolStripMenuItemDelete.Enabled = chk_Modefy.Checked;
            toolStripMenuItemEdit.Enabled = chk_Modefy.Checked;
            pbox_personalImage.Enabled = chk_Modefy.Checked;
            if (chk_Modefy.Checked)
            {
                label11.Text = "العمر";
                chk_Modefy.Text = "  حفظ  ";
            }
            else
            {
                label11.Text = "تاريخ الميلاد";
                chk_Modefy.Text = "تعديل البيانات";
            }
        }
        string imgPath;
        private void chk_Modefy_CheckedChanged(object sender, EventArgs e)
        {
            if (chk_Modefy.Checked)
            {
                GetElementStates();
            }
            else
            {
                if (personId==0)
                {
                    Person p = new Person();
                    Worthy wor = ctx.Worthies.Single(w => w.Id == worthyId);
                    Person wp = ctx.People.Single(c => c.Id == wor.PersonId);
                    
                    p.Amana = txb_Amana.Text;
                    DateTime dob;
                    int doub;
                    if (DateTime.TryParse(txb_BoxDOB.Text, out dob))
                        p.DOB = dob;
                    else if (int.TryParse(txb_BoxDOB.Text, out doub))
                        p.DOB = DateTime.Now.AddYears(-doub);

                    p.POB = txb_BoxPoP.Text;
                    p.FatherName = txb_FatherName.Text;
                    p.FirstName = txb_FirstName.Text;
                    p.LastName = txb_LaNamest.Text;
                    p.MotherName = txb_MotherName.Text;
                    p.NationalNumber = txb_NatNumber.Text;
                    p.Qaid = txb_Qaid.Text;
                    if (cbo_Sex.SelectedIndex == 0)
                        p.Sex = "ذكر";
                    else if (cbo_Sex.SelectedIndex == 1)
                        p.Sex = "أنثى";

                    p.JobTitle = txb_job.Text;
                    p.HealthStatus = txb_healthStatus.Text;
                    if (pbox_personalImage.Image != null)
                        p.PersonalPicture = GetImageFromPicBox(browseImageDialog);
                    wor.People.Add(p);
                    ctx.SaveChanges();
                    ctx.Entry<Person>(p).Reload();
                    GetElementStates();

                }
                else
                {
                    p = ctx.People.Single(c => c.Id == personId);
                    Person wp = ctx.People.Single(c => c.Id == worthyId);
                    p.Amana = txb_Amana.Text;
                    DateTime dob;
                    int doub;
                    if (DateTime.TryParse(txb_BoxDOB.Text, out dob))
                        p.DOB = dob;
                    else if (int.TryParse(txb_BoxDOB.Text, out doub))
                        p.DOB = DateTime.Now.AddYears(-doub);

                    p.POB = txb_BoxPoP.Text;
                    p.FatherName = txb_FatherName.Text;
                    p.FirstName = txb_FirstName.Text;
                    p.LastName = txb_LaNamest.Text;
                    p.MotherName = txb_MotherName.Text;
                    p.NationalNumber = txb_NatNumber.Text;
                    p.Qaid = txb_Qaid.Text;
                    if (cbo_Sex.SelectedIndex == 0)
                        p.Sex = "ذكر";
                    else if (cbo_Sex.SelectedIndex == 1)
                        p.Sex = "أنثى";

                    p.JobTitle = txb_job.Text;
                    p.HealthStatus = txb_healthStatus.Text;
                    if (pbox_personalImage.Image != null)
                        p.PersonalPicture = GetImageFromPicBox(browseImageDialog);
                    ctx.SaveChanges();
                    ctx.Entry<Person>(p).Reload();
                    GetElementStates();


                }

            }
        }

        private void btn_Dispose_Click(object sender, EventArgs e)
        {
            this.Close();
            is_loaded = false;
        }

        private void PersonalForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            is_loaded = false;
           // mainwindow.Updated = true;
            if(mainwindow.is_loaded==true)
            mainwindow.Activate();
        }
        OpenFileDialog browseImageDialog = new OpenFileDialog();
        private void toolStripMenuItemEdit_Click(object sender, EventArgs e)
        {
            try
            {
                // show browse for image, then when choose image process the loading and display
                    browseImageDialog.Filter = "JPG File|*.jpg|PNG File|*.png";
                    if (browseImageDialog.ShowDialog() == DialogResult.OK)
                    {
                        string path = browseImageDialog.FileName;
                        pbox_personalImage.Load(path);
                    }
            }
            catch
            {
                MessageBox.Show("لقد حصل خطأ أثناء حفظ الصورة", "خطأ", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private string trimstring(string str)
        {
            string temp = str.Replace(':', '_');
            temp = temp.Replace(' ', '_');
            return temp;
        }

        private void toolStripMenuItemDelete_Click(object sender, EventArgs e)
        {

            DialogResult result = MessageBox.Show("تأكيد حذف الصورة؟", "تأكيد الحذف", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                if (p.Id > 0)
                {
                    p.PersonalPicture = null;
                    pbox_personalImage.InitialImage = null;
                    pbox_personalImage.Image = null;
                }
            }
        }
        private byte[] GetImageFromPicBox(OpenFileDialog ofp)
        {
            MemoryStream stream = new MemoryStream();
            //handle Write permissions
            using (Bitmap tempImage = new Bitmap(pbox_personalImage.Image))
            {
                if (ofp.FilterIndex == 0)
                {
                    tempImage.Save(stream, ImageFormat.Jpeg);
                }
                else if (ofp.FilterIndex == 1)
                {
                    tempImage.Save(stream, ImageFormat.Png);
                }
                else
                {
                    tempImage.Save(stream, ImageFormat.Gif);
                }
            }

            byte[] pic = stream.ToArray();
            return pic;
        }
        private void ReadtoPictureBox(byte[] pic)
        {
            MemoryStream stream = new MemoryStream(pic);
            pbox_personalImage.Image = Image.FromStream(stream);
        }



        private void toolStripMenuItemShowPicture_Click(object sender, EventArgs e)
        {

        }

        private void btn_print_Click(object sender, EventArgs e)
        {
            frmPersonReports f = new frmPersonReports(personId,fo);
            f.Show();
        }
    }
}
